package com.cn.algorithm.two.back;

public class EightQueen {

    public static void main(String[] args) {
        new EightQueen().queen(4);
    }


    int[] cols;

    int ways;

    public void queen(int queens) {
        if (queens < 1) {
            return;
        }
        cols = new int[queens];
        start(0);
        System.out.println(ways);
    }

    public void start(int row) {
        if (row == cols.length) {
            ways++;
            return;
        }
        for (int col = 0; col < cols.length; col++) {
            if (isValid(row, col)) {
                cols[row] = col;
                start(row + 1);
            }
        }
    }

    public boolean isValid(int row, int col) {
        for (int i = 0; i < row; i++) {
            if (cols[i] == col) {
                return false;
            }
            if ((row - i) == Math.abs(cols[i] - col)) {
                return false;
            }
        }
        return true;
    }
}
